package forkjion;

import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.RecursiveTask;
import java.util.concurrent.TimeUnit;

public class SumForkJoin extends RecursiveTask<Integer> {

    private final static int THRESHOLD=MakeArray.LENGTH/10;
    private int src[];
    private int startIndex;
    private int endIndex;

    public SumForkJoin(int src[],int startIndex,int endIndex){
        this.src=src;
        this.startIndex=startIndex;
        this.endIndex=endIndex;
    }

    @Override
    protected Integer compute() {
        if((endIndex-startIndex)<THRESHOLD){
            int count=0;
            for (int i=startIndex;i<=endIndex;i++){
                try {
                    TimeUnit.MILLISECONDS.sleep(1);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                count+=1;
            }
            return count;
        }else {

            //工作取密  work
            int mid=(endIndex-startIndex)/2;
            SumForkJoin left=new SumForkJoin(src,startIndex,mid);
            SumForkJoin right=new SumForkJoin(src,mid+1,endIndex);
            invokeAll(left,right);
            return left.join()+right.join();
        }
    }

    public static void main(String[] args) {
        //生成ForkJoin池
        ForkJoinPool pool=new ForkJoinPool();
        //生成任务
        SumForkJoin task=new SumForkJoin(MakeArray.getArray(),0,MakeArray.LENGTH-1);

        System.out.println("state calculate...");
        long startTimeMills=System.currentTimeMillis();
        //执行任务并返回结果
        //这是同步计算，异步计算是execute() 异步不需要返回值 继承RecursiveAction类
        int count=pool.invoke(task);

        System.out.println("it takes"+(System.currentTimeMillis()-startTimeMills)+"ms");
    }
}
